package com.huyong.controller;

import com.huyong.entity.User;
import com.huyong.service.UserService;
import com.huyong.vo.Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    private Vo vo = new Vo();
    //查询所有
    @GetMapping("/findAll")
    @ResponseBody
    public List findAll(){
        return userService.findAll();
    }

    //删除一个用户
    @GetMapping("/delete")
    @ResponseBody
    public Vo deleteUser(Long studyCode){
        boolean result = userService.deleteUser(studyCode);
        if (result){
            vo.setStatus(true).setMsg("删除成功！！！");
        }else {
            vo.setStatus(false).setMsg("删除失败,请重试！！！");
        }
        return vo;
    }

    //添加或者修改一个用户
    @PostMapping("/update")
    @ResponseBody
    public Vo addUser(Integer id,String name,Long studyCode,String studyClass,String sex,Integer age){
        if (id!=null){//如果传过来的id有值，则执行修改操作
            User user = new User();
            user.setId(id).setName(name).setAge(age).setSex(sex).setStudyCode(studyCode).setStudyClass(studyClass);
            boolean updateResult = userService.updateUser(user);
            if (updateResult){
                vo.setStatus(true).setMsg("修改成功！！！");
            }else {
                vo.setStatus(false).setMsg("修改失败,请重试！！！");
            }
            return vo;
        }else {//若是用户不存在，则添加
            User user = new User();
            user.setName(name).setAge(age).setSex(sex).setStudyCode(studyCode).setStudyClass(studyClass);
            boolean addResult = userService.addUser(user);
            if (addResult){
                vo.setStatus(true).setMsg("添加成功！！！");
            }else {
                vo.setStatus(false).setMsg("添加失败,请重试！！！");
            }
            return vo;
        }
    }

    //查找一个用户信息
    @GetMapping("/findOne")
    @ResponseBody
    public User findOne(int id){
        return userService.findOne(id);
    }

}
